﻿// Admin.NET 项目的版权、商标、专利和其他相关权利均受相应法律法规的保护。使用本项目应遵守相关法律法规和许可证的要求。
//
// 本项目主要遵循 MIT 许可证和 Apache 许可证（版本 2.0）进行分发和使用。许可证位于源代码树根目录中的 LICENSE-MIT 和 LICENSE-APACHE 文件。
//
// 不得利用本项目从事危害国家安全、扰乱社会秩序、侵犯他人合法权益等法律法规禁止的活动！任何基于本项目二次开发而产生的一切法律纠纷和责任，我们不承担任何责任！

using Admin.NET.Application.Entity;
using Admin.NET.Core.Service;
using Furion.DatabaseAccessor;
using Furion.FriendlyException;
using Mapster;
using Microsoft.AspNetCore.Http;
using SqlSugar;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;

namespace Admin.NET.Application;

/// <summary>
/// 库存盘点服务 🧩
/// </summary>
[ApiDescriptionSettings(ApplicationConst.GroupName, Order = 100)]
public class InventoryService : IDynamicApiController, ITransient
{
    private readonly SqlSugarRepository<Inventory> _inventoryRep;
    private readonly ISqlSugarClient _sqlSugarClient;

    public InventoryService(SqlSugarRepository<Inventory> inventoryRep, ISqlSugarClient sqlSugarClient)
    {
        _inventoryRep = inventoryRep;
        _sqlSugarClient = sqlSugarClient;
    }

    /// <summary>
    /// 分页查询库存盘点 🔖
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("分页查询库存盘点")]
    [ApiDescriptionSettings(Name = "Page"), HttpPost]
    public async Task<SqlSugarPagedList<InventoryOutput>> Page(PageInventoryInput input)
    {
        input.Keyword = input.Keyword?.Trim();
        var query = _inventoryRep.AsQueryable()
            .WhereIF(!string.IsNullOrWhiteSpace(input.Keyword), u => u.InventoryCode.Contains(input.Keyword) || u.InventoryOutcome.Contains(input.Keyword) || u.InventoryGoods.Contains(input.Keyword) || u.AmountProfit.Contains(input.Keyword) || u.OrganizationalStructureId.Contains(input.Keyword) || u.Remark.Contains(input.Keyword) || u.UpFile.Contains(input.Keyword))
            .WhereIF(!string.IsNullOrWhiteSpace(input.InventoryCode), u => u.InventoryCode.Contains(input.InventoryCode.Trim()))
            .WhereIF(!string.IsNullOrWhiteSpace(input.InventoryOutcome), u => u.InventoryOutcome.Contains(input.InventoryOutcome.Trim()))
            .WhereIF(!string.IsNullOrWhiteSpace(input.InventoryGoods), u => u.InventoryGoods.Contains(input.InventoryGoods.Trim()))
            .WhereIF(!string.IsNullOrWhiteSpace(input.AmountProfit), u => u.AmountProfit.Contains(input.AmountProfit.Trim()))
            .WhereIF(!string.IsNullOrWhiteSpace(input.OrganizationalStructureId), u => u.OrganizationalStructureId.Contains(input.OrganizationalStructureId.Trim()))
            .WhereIF(!string.IsNullOrWhiteSpace(input.Remark), u => u.Remark.Contains(input.Remark.Trim()))
            .WhereIF(!string.IsNullOrWhiteSpace(input.UpFile), u => u.UpFile.Contains(input.UpFile.Trim()))
            .WhereIF(input.InboundId != null, u => u.InboundId == input.InboundId)
            .WhereIF(input.InventoryType != null, u => u.InventoryType == input.InventoryType)
            .WhereIF(input.InventoryBeginRange?.Length == 2, u => u.InventoryBegin >= input.InventoryBeginRange[0] && u.InventoryBegin <= input.InventoryBeginRange[1])
            .WhereIF(input.InventoryEndRange?.Length == 2, u => u.InventoryEnd >= input.InventoryEndRange[0] && u.InventoryEnd <= input.InventoryEndRange[1])
            .WhereIF(input.StorageId != null, u => u.StorageId == input.StorageId)
            .WhereIF(input.OutboundId != null, u => u.OutboundId == input.OutboundId)
            .WhereIF(input.InventoryQuantity != null, u => u.InventoryQuantity == input.InventoryQuantity)
            .WhereIF(input.InventorySurplus != null, u => u.InventorySurplus == input.InventorySurplus)
            .WhereIF(input.NumberLosses != null, u => u.NumberLosses == input.NumberLosses)
            .LeftJoin<WarehouseInfo>((u, inbound) => u.InboundId == inbound.Id)
            .Select((u, inbound) => new InventoryOutput
            {
                Id = u.Id,
                InventoryCode = u.InventoryCode,
                InventoryOutcome = u.InventoryOutcome,
                InboundId = u.InboundId,
                InboundFkDisplayName = $"{inbound.WarehouseName}",
                InventoryType = u.InventoryType,
                InventoryBegin = u.InventoryBegin,
                InventoryEnd = u.InventoryEnd,
                StorageId = u.StorageId,
                OutboundId = u.OutboundId,
                InventoryGoods = u.InventoryGoods,
                InventoryQuantity = u.InventoryQuantity,
                InventorySurplus = u.InventorySurplus,
                NumberLosses = u.NumberLosses,
                AmountProfit = u.AmountProfit,
                OrganizationalStructureId = u.OrganizationalStructureId,
                Remark = u.Remark,
                UpFile = u.UpFile,
                IsDelete = u.IsDelete,
                CreateTime = u.CreateTime,
                UpdateTime = u.UpdateTime,
                CreateUserId = u.CreateUserId,
                CreateUserName = u.CreateUserName,
                UpdateUserId = u.UpdateUserId,
                UpdateUserName = u.UpdateUserName,
            });
		return await query.OrderBuilder(input).ToPagedListAsync(input.Page, input.PageSize);
    }

    /// <summary>
    /// 获取库存盘点详情 ℹ️
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("获取库存盘点详情")]
    [ApiDescriptionSettings(Name = "Detail"), HttpGet]
    public async Task<Inventory> Detail([FromQuery] QueryByIdInventoryInput input)
    {
        return await _inventoryRep.GetFirstAsync(u => u.Id == input.Id);
    }

    /// <summary>
    /// 增加库存盘点 ➕
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("增加库存盘点")]
    [ApiDescriptionSettings(Name = "Add"), HttpPost]
    public async Task<long> Add(AddInventoryInput input)
    {
        var entity = input.Adapt<Inventory>();
        return await _inventoryRep.InsertAsync(entity) ? entity.Id : 0;
    }

    /// <summary>
    /// 更新库存盘点 ✏️
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("更新库存盘点")]
    [ApiDescriptionSettings(Name = "Update"), HttpPost]
    public async Task Update(UpdateInventoryInput input)
    {
        var entity = input.Adapt<Inventory>();
        await _inventoryRep.AsUpdateable(entity)
        .ExecuteCommandAsync();
    }

    /// <summary>
    /// 删除库存盘点 ❌
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("删除库存盘点")]
    [ApiDescriptionSettings(Name = "Delete"), HttpPost]
    public async Task Delete(DeleteInventoryInput input)
    {
        var entity = await _inventoryRep.GetFirstAsync(u => u.Id == input.Id) ?? throw Oops.Oh(ErrorCodeEnum.D1002);
        await _inventoryRep.FakeDeleteAsync(entity);   //假删除
        //await _inventoryRep.DeleteAsync(entity);   //真删除
    }

    /// <summary>
    /// 批量删除库存盘点 ❌
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("批量删除库存盘点")]
    [ApiDescriptionSettings(Name = "BatchDelete"), HttpPost]
    public async Task<int> BatchDelete([Required(ErrorMessage = "主键列表不能为空")]List<DeleteInventoryInput> input)
    {
        var exp = Expressionable.Create<Inventory>();
        foreach (var row in input) exp = exp.Or(it => it.Id == row.Id);
        var list = await _inventoryRep.AsQueryable().Where(exp.ToExpression()).ToListAsync();
   
        return await _inventoryRep.FakeDeleteAsync(list);   //假删除
        //return await _inventoryRep.DeleteAsync(list);   //真删除
    }
    
    /// <summary>
    /// 获取下拉列表数据 🔖
    /// </summary>
    /// <returns></returns>
    [DisplayName("获取下拉列表数据")]
    [ApiDescriptionSettings(Name = "DropdownData"), HttpPost]
    public async Task<Dictionary<string, dynamic>> DropdownData(DropdownDataInventoryInput input)
    {
        var inboundIdData = await _inventoryRep.Context.Queryable<WarehouseInfo>()
            .InnerJoinIF<Inventory>(input.FromPage, (u, r) => u.Id == r.InboundId)
            .Select(u => new {
                Value = u.Id,
                Label = $"{u.WarehouseName}"
            }).ToListAsync();
        return new Dictionary<string, dynamic>
        {
            { "inboundId", inboundIdData },
        };
    }
    
    /// <summary>
    /// 导出库存盘点记录 🔖
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("导出库存盘点记录")]
    [ApiDescriptionSettings(Name = "Export"), HttpPost, NonUnify]
    public async Task<IActionResult> Export(PageInventoryInput input)
    {
        var list = (await Page(input)).Items?.Adapt<List<ExportInventoryOutput>>() ?? new();
        if (input.SelectKeyList?.Count > 0) list = list.Where(x => input.SelectKeyList.Contains(x.Id)).ToList();
        return ExcelHelper.ExportTemplate(list, "库存盘点导出记录");
    }
    
    /// <summary>
    /// 下载库存盘点数据导入模板 ⬇️
    /// </summary>
    /// <returns></returns>
    [DisplayName("下载库存盘点数据导入模板")]
    [ApiDescriptionSettings(Name = "Import"), HttpGet, NonUnify]
    public IActionResult DownloadTemplate()
    {
        return ExcelHelper.ExportTemplate(new List<ExportInventoryOutput>(), "库存盘点导入模板", (_, info) =>
        {
            if (nameof(ExportInventoryOutput.InboundFkDisplayName) == info.Name) return _inventoryRep.Context.Queryable<WarehouseInfo>().Select(u => $"{u.WarehouseName}").Distinct().ToList();
            return null;
        });
    }
    
    /// <summary>
    /// 导入库存盘点记录 💾
    /// </summary>
    /// <returns></returns>
    [DisplayName("导入库存盘点记录")]
    [ApiDescriptionSettings(Name = "Import"), HttpPost, NonUnify, UnitOfWork]
    public IActionResult ImportData([Required] IFormFile file)
    {
        lock (this)
        {
            var stream = ExcelHelper.ImportData<ImportInventoryInput, Inventory>(file, (list, markerErrorAction) =>
            {
                _sqlSugarClient.Utilities.PageEach(list, 2048, pageItems =>
                {
                    // 链接 仓库名称ID
                    var inboundIdLabelList = pageItems.Where(x => x.InboundFkDisplayName != null).Select(x => x.InboundFkDisplayName).Distinct().ToList();
                    if (inboundIdLabelList.Any()) {
                        var inboundIdLinkMap = _inventoryRep.Context.Queryable<WarehouseInfo>().Where(u => inboundIdLabelList.Contains($"{u.WarehouseName}")).ToList().ToDictionary(u => $"{u.WarehouseName}", u => u.Id);
                        pageItems.ForEach(e => {
                            e.InboundId = inboundIdLinkMap.GetValueOrDefault(e.InboundFkDisplayName ?? "");
                            if (e.InboundId == null) e.Error = "仓库名称ID链接失败";
                        });
                    }
                    
                    // 校验并过滤必填基本类型为null的字段
                    var rows = pageItems.Where(x => {
                        return true;
                    }).Adapt<List<Inventory>>();
                    
                    var storageable = _inventoryRep.Context.Storageable(rows)
                        .SplitError(it => it.Item.InventoryCode?.Length > 32, "盘点单号长度不能超过32个字符")
                        .SplitError(it => it.Item.InventoryOutcome?.Length > 32, "盘点结果长度不能超过32个字符")
                        .SplitError(it => it.Item.InventoryGoods?.Length > 32, "盘点货品长度不能超过32个字符")
                        .SplitError(it => it.Item.AmountProfit?.Length > 32, "盘盈金额长度不能超过32个字符")
                        .SplitError(it => it.Item.OrganizationalStructureId?.Length > 32, "经办人ID长度不能超过32个字符")
                        .SplitError(it => it.Item.Remark?.Length > 32, "备注长度不能超过32个字符")
                        .SplitError(it => it.Item.UpFile?.Length > 64, "上传文件长度不能超过64个字符")
                        .SplitInsert(_ => true)
                        .ToStorage();
                    
                    storageable.BulkCopy();
                    storageable.BulkUpdate();
                    
                    // 标记错误信息
                    markerErrorAction.Invoke(storageable, pageItems, rows);
                });
            });
            
            return stream;
        }
    }
}
